Skip to content

Conversation

@jezzzm
Copy link
Contributor

@jezzzm jezzzm commented Oct 29, 2025

Pull Request

Related issue

Fixes #1417

What does this PR do?

  • defends against missing value key in some attributes for highlighting
  • specifically: non-primitive values (or arrays of non-primitives) may not include value as a key

PR checklist

Please check if your PR fulfills the following requirements:

  • Does this PR fix an existing issue, or have you listed the changes applied in the PR description (and why they are needed)?
  • Have you read the contributing guidelines?
  • Have you made sure that the title is accurate and descriptive of the changes?

Thank you so much for contributing to Meilisearch!

Summary by CodeRabbit

  • Refactor
    • Improved handling of search result highlighting so missing or undefined fields are now skipped, producing more accurate highlights.
  • Tests
    • Added coverage to ensure highlight behavior ignores attributes without values.
  • Chores
    • Expanded test data to include nested review entries for more realistic test scenarios.

@changeset-bot
Copy link

changeset-bot bot commented Oct 29, 2025

⚠️ No Changeset found

Latest commit: a50dfa9

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link

coderabbitai bot commented Oct 29, 2025

Walkthrough

Adds runtime guards and new union types to skip undefined/non-primitive Meilisearch _highlightResult entries, refactors highlight mapping to mutate an accumulator only when highlight value is present, and adds a test plus sample data with nested reviews.

Changes

Cohort / File(s) Change Summary
Highlight parsing & type safety
packages/autocomplete-client/src/search/fetchMeilisearchResults.ts
Introduces PossibleHighlightResult plus DefinedHighlightResult/UndefinedHighlightResult, adds isDefinedHighlightValue runtime guard, refactors reduce logic to mutate a highlights accumulator only for defined values, and adapts calls to mapOneOrMany and calculateHighlightMetadata.
Test fixtures updated
packages/autocomplete-client/__tests__/test.utils.ts
Adds a reviews array (two review objects) to multiple movie entries in the exported MOVIES test data, changing the shape of those records.
Tests
packages/autocomplete-client/src/search/__tests__/fetchMeilisearchResults.test.ts
Adds test "highlight results skips attributes missing value key" asserting _highlightResult.reviews is undefined when Meilisearch returns non-primitive highlight entries without a value key.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant fetchFn as fetchMeilisearchResults
  participant Guard as isDefinedHighlightValue
  participant Mapper as mapOneOrMany
  participant Meta as calculateHighlightMetadata

  Client->>fetchFn: request search results
  fetchFn->>fetchFn: receive raw _highlightResult
  loop per attribute
    fetchFn->>Guard: check attribute highlight entry
    alt defined value
      Guard-->>fetchFn: true
      fetchFn->>Mapper: map one or many values
      Mapper-->>Meta: for each value compute metadata
      Meta-->>fetchFn: metadata
      fetchFn->>fetchFn: assign acc[field] = metadata
    else undefined / non-primitive
      Guard-->>fetchFn: false
      fetchFn->>fetchFn: skip attribute (no assignment)
    end
  end
  fetchFn-->>Client: return results with sanitized highlights
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Pay attention to: isDefinedHighlightValue correctness and edge cases (arrays vs single values), mutation in reducer to ensure no accidental reference sharing, adjustments to tests and test fixtures for shape changes.

Poem

🐰
Hops through results with cautious care,
I skip the values that simply aren't there.
I map the good bits, leave the rest to rest —
A tidy highlight, now passing the test! ✨

Pre-merge checks and finishing touches

✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "fix(autocomplete): gracefully handle missing values when parsing highlights" directly and specifically describes the main change in the pull request. The modifications add defensive handling through the isDefinedHighlightValue guard to skip processing when value fields are missing from highlight results, which aligns precisely with the phrase "gracefully handle missing values when parsing highlights." The title is concise, clear, and provides meaningful context without being overly verbose.
Linked Issues Check ✅ Passed The pull request addresses the primary coding objective from issue #1417: adding defensive checks in the autocomplete highlight parsing for the existence of a valid value key. The implementation includes a new isDefinedHighlightValue function that acts as a runtime guard to skip processing for undefined highlight results [#1417], along with a corresponding test case "highlight results skips attributes missing value key" that validates the fix. The test data changes support this new test scenario by adding a reviews field that demonstrates non-primitive data without value keys. While issue #1417 also mentions a desired server-side fix to ensure _highlightResult only contains specified attributes, the minimum requirement of robust client-side parsing is fully met.
Out of Scope Changes Check ✅ Passed All code changes in the pull request are directly scoped to addressing issue #1417. The fetchMeilisearchResults.ts modifications introduce the defensive handling logic for missing values, the test.utils.ts changes augment test data with a reviews field to provide realistic test scenarios with non-primitive values, and the test file adds a specific test case validating the fix. Each change contributes directly to the objective of gracefully handling missing value keys in highlight results, with no extraneous modifications.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 215601a and a50dfa9.

📒 Files selected for processing (3)
  • packages/autocomplete-client/__tests__/test.utils.ts (6 hunks)
  • packages/autocomplete-client/src/search/__tests__/fetchMeilisearchResults.test.ts (1 hunks)
  • packages/autocomplete-client/src/search/fetchMeilisearchResults.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
packages/autocomplete-client/src/search/fetchMeilisearchResults.ts (1)
packages/autocomplete-client/src/constants/index.ts (2)
  • HIGHLIGHT_PRE_TAG (1-1)
  • HIGHLIGHT_POST_TAG (2-2)
packages/autocomplete-client/src/search/__tests__/fetchMeilisearchResults.test.ts (1)
packages/autocomplete-client/src/search/fetchMeilisearchResults.ts (1)
  • fetchMeilisearchResults (34-95)
🔇 Additional comments (6)
packages/autocomplete-client/__tests__/test.utils.ts (1)

29-95: LGTM! Test data appropriately enhanced.

The addition of the reviews field (arrays of objects) to all movie entries provides the necessary test data for verifying that non-primitive fields without a value key in _highlightResult are handled gracefully.

packages/autocomplete-client/src/search/fetchMeilisearchResults.ts (4)

149-151: LGTM! Clean helper function.

The mapOneOrMany helper elegantly handles both single values and arrays, maintaining type consistency in the return value.


153-164: Type definitions correctly model the highlight result variants.

The union types properly distinguish between defined and undefined highlight results. The value?: never pattern in UndefinedHighlightResult is unconventional but works effectively for type narrowing when combined with the runtime guard.

The comment provides helpful context about the server behavior and the defensive approach taken.


166-174: LGTM! Robust type guard implementation.

Using typeof r.value === 'string' is excellent because it handles null, undefined, and any non-string types in a single check. The type predicate correctly narrows PossibleHighlightResult to DefinedHighlightResult, ensuring type safety downstream.

The array handling with .every() ensures that all elements must have valid string values, or the entire field is skipped—a conservative and safe approach aligned with the PR objectives.


67-87: LGTM! Defensive highlight processing implemented correctly.

The refactored logic gracefully handles missing values:

  1. The type guard at line 70 provides an early exit for undefined highlight results
  2. After the guard, TypeScript correctly narrows the type to DefinedHighlightResult
  3. The accumulator is only mutated when valid highlight data exists (line 75)
  4. mapOneOrMany correctly handles both single values and arrays
  5. The callback safely accesses .value (line 82) since the type has been narrowed

This implementation directly addresses the PR objectives by preventing type errors when non-primitive fields lack a value property.

packages/autocomplete-client/src/search/__tests__/fetchMeilisearchResults.test.ts (1)

188-200: LGTM! Test case validates the defensive handling.

This test directly verifies that highlight results gracefully skip attributes lacking a value key. The expectation that _highlightResult?.reviews is undefined confirms that non-primitive fields (arrays of objects) are handled without errors, which addresses the core issue #1417.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 043669a and 215601a.

📒 Files selected for processing (1)
  • packages/autocomplete-client/src/search/fetchMeilisearchResults.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/autocomplete-client/src/search/fetchMeilisearchResults.ts (1)
packages/autocomplete-client/src/constants/index.ts (2)
  • HIGHLIGHT_PRE_TAG (1-1)
  • HIGHLIGHT_POST_TAG (2-2)
🔇 Additional comments (3)
packages/autocomplete-client/src/search/fetchMeilisearchResults.ts (3)

153-164: LGTM: Type definitions correctly model the problem.

The union type structure cleanly handles both scalar and array highlight results that may or may not have a value property. The comment usefully documents the server behavior this is working around.


67-88: LGTM: Defensive handling and clean refactoring.

The early return on lines 70-72 gracefully skips highlight results without defined values, preventing type errors. The refactored logic using mapOneOrMany and direct mutation of the accumulator is both clearer and more efficient than creating intermediate objects.

Line 82's access to highlightResult.value is safe because isDefinedHighlightValue has confirmed its presence.


148-151: LGTM: Clean, reusable helper.

The mapOneOrMany abstraction correctly handles both scalar and array values with appropriate type inference.

@Strift
Copy link
Collaborator

Strift commented Nov 3, 2025

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Nov 3, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@Strift Strift added the bug Something isn't working label Nov 3, 2025
Copy link
Collaborator

@Strift Strift left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello @jezzzm and thank you for your contribution 🙌

@Strift Strift added this pull request to the merge queue Nov 3, 2025
Merged via the queue into meilisearch:main with commit 19999a9 Nov 3, 2025
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

autocomplete highlighting type errors when handling fields with non-primitive values

2 participants